package com.honghu.villagepost.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.ada.common.util.CollectionUtil
import com.ada.common.util.GsonUtil
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken
import com.honghu.villagepost.R
import com.honghu.villagepost.adapter.OrderGoodsAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseActivity
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.constant.Constants
import com.honghu.villagepost.entity.Addr
import com.honghu.villagepost.entity.OrderDetails
import com.honghu.villagepost.entity.WeixinPayEven
import com.honghu.villagepost.util.CopyUtil
import com.honghu.villagepost.widget.PayPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_order_logistics_details.*
import kotlinx.android.synthetic.main.activity_submit_order.*
import kotlinx.android.synthetic.main.activity_submit_order.layout_bottom
import kotlinx.android.synthetic.main.activity_submit_order.tv_order_no
import kotlinx.android.synthetic.main.activity_submit_order.tv_order_remark
import kotlinx.android.synthetic.main.activity_submit_order.tv_pay
import kotlinx.android.synthetic.main.activity_submit_order.tv_status
import kotlinx.android.synthetic.main.activity_submit_order.tv_total
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author: mqwang
 * @create: 2/9/21 5:50 PM
 * @Description: 提交订单
 */
class OrderDetailsActivity : BaseActivity() {

    private var orderNo: String? = null
    private var orderDetails: OrderDetails? = null
    private var addressId: Int? = null
    private var settleItemList: String? = null
    private var shopId: Int? = null
    private var payPopup: BasePopupView? = null
    private val orderGoodsAdapter: OrderGoodsAdapter by lazy {
        OrderGoodsAdapter()
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    companion object {
        fun self(context: Context, shopId: Int, settleItemList: String) {
            val intent = Intent(context, OrderDetailsActivity::class.java)
            intent.putExtra(Constants.SHOP_ID, shopId)
            intent.putExtra(Constants.GOODS_LIST, settleItemList)
            context.startActivity(intent)
        }

        fun self(context: Context, orderId: String) {
            val intent = Intent(context, OrderDetailsActivity::class.java)
            intent.putExtra(Constants.ORDER_ID, orderId)
            context.startActivity(intent)
        }
    }


    override fun getLayoutId(): Int {
        return R.layout.activity_submit_order
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {

        setMainTitle("提交订单")

        shopId = intent.getIntExtra(Constants.SHOP_ID, 0)
        settleItemList = intent.getStringExtra(Constants.GOODS_LIST)

        orderNo = intent.getStringExtra(Constants.ORDER_ID)

        recycler_view.adapter = orderGoodsAdapter
        layout_addr.setOnClickListener {
            AddrActivity.self(this, true)
        }

        tv_pay.setOnClickListener {
            if (ObjectUtils.isEmpty(addressId) && !ObjectUtils.isEmpty(settleItemList)) {
                ToastUtils.showShort("请选择地址")
                return@setOnClickListener
            }

            val parseList = GsonUtil.parseList<MutableMap<String, Any>>(settleItemList, object : TypeToken<MutableList<MutableMap<String?, Any>>>() {}.type)
            if (!TextUtils.isEmpty(orderNo)){
                weixPay(orderNo!!)
            }else{
                ApiService.order_create(this, addressId, et_mark.text.toString(), parseList, shopId, object : DialogCallback<LzyResponse<MutableMap<String, Any>>>() {
                    override fun onSuccess(response: Response<LzyResponse<MutableMap<String, Any>>>?) {
                        orderNo = response!!.body().data.get("orderNo") as String?
                        showPayPopup()
                    }
                })
            }
        }

        getDefaultAddr()

        if (ObjectUtils.isEmpty(orderNo)) {
            orderSettle()
        } else {
            orderDetails()
        }

    }

    private fun getDefaultAddr() {
        ApiService.user_address(this, "", 1, object : DialogCallback<LzyResponse<Addr>>(this) {
            override fun onSuccess(response: Response<LzyResponse<Addr>>?) {
                val records = response!!.body().data.records
                val defaultAddr = getDefaultAddr(records)
                if (defaultAddr != null) {
                    tv_addr.setText(defaultAddr.province + defaultAddr.city + defaultAddr.district)
                    tv_name.setText(defaultAddr.name + "   " + defaultAddr.mobile)
                    addressId = defaultAddr.id
                }
            }
        })
    }

    private fun getDefaultAddr(records: List<Addr>): Addr? {
        if (!CollectionUtil.isEmptyOrNull(records)) {
            for (addr in records) {
                if (addr!!.defaultAddr) {
                    return addr
                }
            }
            return records[0]
        }
        return null
    }

    fun showPayPopup() {
        payPopup = XPopup.Builder(this)
                .autoOpenSoftInput(true)
                .setPopupCallback(object : SimpleCallback() {
                    override fun onDismiss(popupView: BasePopupView?) {
                        super.onDismiss(popupView)
                        orderDetails()
                    }
                })
                .asCustom(PayPopup(this, PayPopup.OnClick {
                    weixPay(orderNo!!)
                }))
                .show()

    }

    private fun weixPay(orderNo: String) {
        ApiService.order_pay_wx(this, orderNo, object : DialogCallback<LzyResponse<Map<String, String>>>(mContext) {
            override fun onSuccess(response: Response<LzyResponse<Map<String, String>>>?) {
                payPopup?.dismiss()
                val api = WXAPIFactory.createWXAPI(mContext, Constants.WEIXIN_APP_ID)
                val req = PayReq()
                //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                req.appId = response!!.body().data["appid"]
                req.partnerId = response!!.body().data["partnerid"]
                req.prepayId = response!!.body().data["prepayid"]
                req.nonceStr = response!!.body().data["noncestr"]
                req.timeStamp = response!!.body().data["timestamp"]
                req.packageValue = response!!.body().data["package"]
                req.sign = response!!.body().data["sign"]
                api.sendReq(req)
            }

        })
    }

    /** 订单详情 */
    fun orderDetails() {
        ApiService.order_details(this, orderNo, object : DialogCallback<LzyResponse<OrderDetails>>(this) {
            override fun onSuccess(response: Response<LzyResponse<OrderDetails>>?) {
                group_details.visibility = View.VISIBLE
                group_create.visibility = View.GONE

                orderDetails = response!!.body().data as OrderDetails

                setMainTitle("订单详情")

                tv_fee.setText(getString(R.string.price_format, orderDetails!!.postFee))
                tv_total2.setText(getString(R.string.price_format, orderDetails!!.totalFee))

                tv_receiver_info.setText(orderDetails!!.receiverName)
                tv_order_no.setText(orderDetails!!.orderNo)

                tv_order_no.setOnClickListener {
                    CopyUtil.ClipData(mContext, orderDetails!!.orderNo)
                }
                tv_order_date.setText(orderDetails!!.payTime)
                tv_order_date.setText(orderDetails!!.payTime)
                tv_order_remark.setText(orderDetails!!.buyerMemo)

                when (orderDetails!!.state) {
                    //等待买家付款
                    1 -> {
                        tv_status.setText("订单待付款")
                    }
                    //2-买家已付款, 3-等待卖家发货,即:买家已付款, 4-卖家发货中, 5-卖家部分发货, 6-等待买家确认收货,即:卖家已发货
                    2, 3, 4, 5, 6 -> {
                        tv_status.setText("订单已付款")
                        layout_bottom.visibility = View.GONE
                    }
                    //10-交易成功,即:卖家已发货,11-交易成功,即:卖家已发货,12-交易被系统关闭
                    10, 11, 12 -> {
                        tv_status.setText("订单已完成")
                        layout_bottom.visibility = View.GONE
//                        //骑手信息
                    }
                }
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun weixinPay(weixinPayEven: WeixinPayEven) {
        setResult(RESULT_OK)
        when (weixinPayEven.code) {
            0 -> {
                showToast("支付成功")
                finish()

            }
            -1 -> showToast("未知错误")
            -2 -> showToast("用户取消")
            else -> {
            }
        }
    }

    /** 订单结算 */
    fun orderSettle() {
        val parseList = GsonUtil.parseList<MutableMap<String, Any>>(settleItemList, object : TypeToken<MutableList<MutableMap<String?, Any>>>() {}.type)
        ApiService.order_settle(this, addressId, parseList, shopId, object : DialogCallback<LzyResponse<OrderDetails>>() {
            override fun onSuccess(response: Response<LzyResponse<OrderDetails>>?) {
                var orderDetails = response!!.body().data
                if (!ObjectUtils.isEmpty(orderDetails.settleItemList)) {
                    orderGoodsAdapter.setNewData(orderDetails.settleItemList)
                }
                tv_store_name.setText(orderDetails.shopName)
                tv_total.setText(getString(R.string.price_format, orderDetails.totalFee))
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: Addr) {
        tv_addr.setText(item!!.province + item!!.city + item!!.district)
        tv_name.setText(item!!.name + "   " + item!!.mobile)
        addressId = item.id

    }
}